Python Difference Between Two Dates in Months [2 Ways]– PYnative 您所在的位置:网站首页 Time Duration Calculator Time between two datestimes Python Difference Between Two Dates in Months [2 Ways]– PYnative

Python Difference Between Two Dates in Months [2 Ways]– PYnative

2023-01-09 23:56| 来源: 网络整理| 查看: 265

Python Difference Between Two Dates in Months and Years

Updated on: May 6, 2022 | 1 Comment

After reading this article, you’ll learn how to find years and months between two dates in Python.

Table of contentsHow to calculate years and months between two datesExample: Get Years, Months, and Days between two datesExample: Get Only Months between two datesDifference between two dates in months using datetime moduleCalculate months between two datetime objects

Also, see the difference between two dates in days in Python.

How to calculate years and months between two dates

Python dateutil module provides a relativedelta class, representing an interval of time. For example, we can find the difference between two dates in year, months, days, hours, minutes, seconds, and microseconds using the relativedelta class. The Below steps show how to determine the number of years and months between two dates or datetime objects.

Import dateutil module

The dateutil is a third-party module that provides powerful extensions to the standard datetime module, available in Python.

Convert date string to a datetime object

If a date is in a string format, we need to convert a string to a datetime object before calculating the difference in months. Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format. For example, the string can be in the format of yyyy-mm-dd.

Create a relativedelta object

Create a relativedelta object that represents the interval between two given dates. Use the relativedelta(end_date, start_date) function of a dateutil module to create a relativedelta object.

Get Years, Months, and Days between two dates

Use the relativedelta.years attribute to get years.Next, Use the relativedelta.months to get months. In the end, use relativedelta.days to get days.

Get only months between two dates

Use the relativedelta.months + relativedelta.years * 12 formula to get the total months between two dates.

Example: Get Years, Months, and Days between two dates

Let’s assume we have two dates, ’14/8/2019′ and ’16/3/2022′. After executing the below example, we should get the difference of 2 Years, 7 months, and 2 days between two dates.

from datetime import datetime from dateutil import relativedelta # get two dates d1 = '14/8/2019' d2 = '16/3/2022' # convert string to date object start_date = datetime.strptime(d1, "%d/%m/%Y") end_date = datetime.strptime(d2, "%d/%m/%Y") # Get the relativedelta between two dates delta = relativedelta.relativedelta(end_date, start_date) print('Years, Months, Days between two dates is') print(delta.years, 'Years,', delta.months, 'months,', delta.days, 'days')

Output:

Years, Months, Days between two dates is 2 Years, 7 months, 2 days Example: Get Only Months between two dates

Note: The relativedelta.months return the relative difference, i.e., from 0 to 12. So to get an absolute number, we need to calculate the number of years between two dates, multiply them by 12 and add them to relativedelta.months.

from datetime import datetime from dateutil import relativedelta # get two dates d1 = '14/8/2019' d2 = '16/3/2022' # convert string to date object start_date = datetime.strptime(d1, "%d/%m/%Y") end_date = datetime.strptime(d2, "%d/%m/%Y") # Get the relativedelta between two dates delta = relativedelta.relativedelta(end_date, start_date) # get months difference res_months = delta.months + (delta.years * 12) print('Total Months between two dates is:', res_months)

Output:

Total Months between two dates is: 31

Also, see Calculate the number of days between two dates in Python.

Difference between two dates in months using datetime module

Instead of using the dateutil module, we can use the built-in datetime module to get calendar months between two dates.

Use the below formula to calculate.

res = (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month)

Example:

from datetime import datetime date_1 = '24/12/2021' date_2 = '26/3/2022' start = datetime.strptime(date_1, "%d/%m/%Y") end = datetime.strptime(date_2, "%d/%m/%Y") res = (end.year - start.year) * 12 + (end.month - start.month) print('Difference between dates in months:', res)

Output:

Difference between dates in months: 3

Note:

Use the datetime module when you need a difference in the calendar month. Don’t use the datetime module to calculate the exact months between two dates.

For example, the difference between ’30/1/2022′ and ‘1/2/2022’ is 2 days, but the above example shows 1 month. So always use the dateutil module to get the correct results.

Example 1: Datetime module

from datetime import datetime from dateutil import relativedelta start = datetime.strptime('30/1/2022', "%d/%m/%Y") end = datetime.strptime('1/2/2022', "%d/%m/%Y") res = (end.year - start.year) * 12 + (end.month - start.month) print('Months between two dates is:', res) # Output 1

Example 2: Dateutil module

from datetime import datetime from dateutil import relativedelta start_date = datetime.strptime('30/1/2022', "%d/%m/%Y") end_date = datetime.strptime('1/2/2022', "%d/%m/%Y") delta = relativedelta.relativedelta(end_date, start_date) res_months = delta.months + (delta.years * 12) print('Months between two dates is:', res_months) # Output 0 Calculate months between two datetime objects

There are cases in which you receive dates in a datetime object instead of a string. In such cases, you don’t need to convert them. You can directly calculate the difference between them.

Example:

from datetime import datetime # datetime in year-month-day-hour-minute-second-microsecond format start = datetime(2021, 10, 20, 9, 15, 32, 36980) end = datetime(2022, 2, 20, 4, 25, 42, 120450) res = (end.year - start.year) * 12 + (end.month - start.month) print('Difference between dates in months:', res)

Output:

Difference between dates in months: 4

Filed Under: Python, Python DateTime



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有